<template>
  <div class="messages" @scroll="handleScroll" @click="handleClick($event)">
    <messageItem
      v-for="(message, key) in messages"
      :key="key"
      :message="message"
      @quote="handleQuote"
    ></messageItem>
  </div>
  <reply :message="quote" v-model:visible="showReply" />
</template>

<script setup>
import Viewer from "viewerjs"
import "viewerjs/dist/viewer.css"
import messageItem from './MessageItem.vue'
import reply from './Reply.vue'
import { defineComponent, toRefs, watch, nextTick, reactive } from 'vue'

const props = defineProps({
  pagination: {
    type: Object,
    required: true
  },
  messages: {
    type: Array,
    required: true
  },
  conversation: {
    type: Object,
    required: true
  },
})

const emit = defineEmits(['loadMore'])

const state = reactive({
  showReply: true,
  quote: {
    owner: null,
    content: null,
    type: null,
  }
})
//控制滚动条滚动方向
let scrollTo = 'bottom'

const handleScroll = (e) => {
  //滚动条滚动到顶部的时候,分页加载数据
  if (e.target.scrollTop === 0 && props.pagination.hasMore) {
    scrollTo = 'top'
    emit('loadMore', props.conversation.id)
  }
}

const handleClick = (e) => {
  //图片预览
  if (e.target.classList.contains("viewer-img")) {
    const viewer = new Viewer(e.target, {
      button: true,
      loading: true,
    });
    viewer.show();
  }
}

const handleQuote = ({ content, type, from }) => {
  state.showReply = true
  state.quote.content = content
  state.quote.type = type
  if (from == 1) {
    state.quote.owner = props.conversation.guest.name
  } else {
    state.quote.owner = "客服"
  }
}

//当消息列表有变化时,滚动条也要做相应的变化
watch(() => [...props.messages], (data) => {
  nextTick(() => {
    setTimeout(() => {
      //根据设置的滚动方向,向上或向下滚动,向上滚动是因为上拉加载分页数据后我们需要滚动条保留在历史位置
      if (scrollTo === 'top') {
        let destination = document.querySelectorAll('.message-item')[props.pagination.pageSize];
        destination && destination.scrollIntoView()
        scrollTo = 'bottom'
      } else {
        const lastItem = document.querySelector('.message-item:last-child')
        lastItem && lastItem.scrollIntoView()
      }
    }, 300)
  })
})

const { showReply, quote } = toRefs(state)

</script>
<style scoped>
.messages {
  flex: 1;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: auto;
  height: 100%;
  margin: 0;
}
</style>
